import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { getPatientByUserId, type PatientCard } from "@/api/patient";

// 预约信息接口
interface AppointmentInfo {
  id: number;
  orderNo: string;
  department: string;
  departmentId: string;
  doctorName: string;
  doctorId: string;
  date: string;
  time: string;
  fee: number;
  status: '待支付' | '待就诊' | '已完成' | '已取消';
  createTime: string;
  notes?: string;
  // 新增后端返回的字段
  appointmentId?: string;  // 后端预约ID
  slotNo?: number;        // 诊号
  clnicId?: number;       // 医生坐诊ID（取消预约需要）
}

// 新增：就诊卡接口
interface MedicalCard {
  id: number;
  patientName: string;
  idNumber: string;
  maskedIdNumber: string;
  isDefault: boolean;
  isSelf: boolean;
}

// 慢病信息接口
interface ChronicDisease {
  id: number;
  name: string;
  type: string;
  diagnosisDate: string;
  hospital: string;
  doctor: string;
  severity: string;
  status: 'active' | 'stable' | 'recovered';
  createTime: string;
}

// 健康数据接口
interface HealthMetric {
  id: number;
  type: 'blood_pressure' | 'blood_sugar' | 'weight' | 'heart_rate';
  value: string;
  unit: string;
  recordTime: string;
  notes?: string;
}

// 处方信息接口
interface Prescription {
  id: number;
  prescriptionNo: string;
  doctorName: string;
  department: string;
  date: string;
  status: '待取药' | '已取药' | '已过期';
  totalPrice: number;
  medicines: Array<{
    name: string;
    spec: string;
    quantity: number;
    usage: string;
  }>;
}

// 新增：医院信息接口
interface HospitalInfo {
  deptId: string;
  deptName: string;
}

export const useMedicalStore = defineStore("medical", () => {
  // 预约记录
  const appointments = ref<AppointmentInfo[]>([]);
  
  // 新增：当前选中的就诊卡
  const currentMedicalCard = ref<MedicalCard | null>(null);
  
  // 新增：当前预约
  const currentAppointment = ref<AppointmentInfo | null>(null);
  
  // 慢病档案
  const chronicDiseases = ref<ChronicDisease[]>([]);
  
  // 健康数据
  const healthMetrics = ref<HealthMetric[]>([]);
  
  // 处方记录
  const prescriptions = ref<Prescription[]>([]);

  // 就诊卡列表
  const patientCards = ref<PatientCard[]>([]);

  // 新增：当前选择的医院信息
  const currentHospital = ref<HospitalInfo | null>(null);

  const upcomingAppointments = computed(() => {
    return appointments.value.filter(apt => apt.status === '待就诊' || apt.status === '待支付');
  });
  
  const pendingPaymentAppointments = computed(() => {
    return appointments.value.filter(apt => apt.status === '待支付');
  });

  const activeChronicDiseases = computed(() => {
    return chronicDiseases.value.filter(disease => disease.status === 'active');
  });

  const recentHealthMetrics = computed(() => {
    return healthMetrics.value.slice(0, 10).sort((a, b) => 
      new Date(b.recordTime).getTime() - new Date(a.recordTime).getTime()
    );
  });

  const pendingPrescriptions = computed(() => {
    return prescriptions.value.filter(p => p.status === '待取药');
  });

  // 新增：就诊卡相关方法
  const setCurrentMedicalCard = (card: MedicalCard) => {
    currentMedicalCard.value = card;
    console.log('设置当前就诊卡:', card);
  };

  const clearCurrentMedicalCard = () => {
    currentMedicalCard.value = null;
    console.log('清空当前就诊卡');
  };

  const getCurrentMedicalCard = () => {
    return currentMedicalCard.value;
  };

  // 新增：就诊卡列表相关方法
  const setPatientCards = (list: PatientCard[]) => {
    patientCards.value = list;
  };

  const fetchPatientCards = async (userId: string) => {
    try {
      const res = await getPatientByUserId(userId);
      if (res.code === 200) {
        patientCards.value = res.data || [];
        console.log('获取就诊卡成功:', res.data);
      } else {
        uni.showToast({ title: res.msg || "获取就诊卡失败", icon: "none" });
        patientCards.value = [];
      }
    } catch (error) {
      console.error('获取就诊卡失败:', error);
      uni.showToast({ title: "网络错误，请重试", icon: "none" });
      patientCards.value = [];
    }
  };

  // 新增：当前预约相关方法
  const setCurrentAppointment = (appointment: Omit<AppointmentInfo, 'id' | 'createTime'>) => {
    const newAppointment: AppointmentInfo = {
      ...appointment,
      id: Date.now() + Math.random(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
    };
    currentAppointment.value = newAppointment;
    return newAppointment;
  };

  const getCurrentAppointment = () => currentAppointment.value;

  const clearCurrentAppointment = () => {
    currentAppointment.value = null;
  };

  // 预约相关方法
  const addAppointment = (appointment: Omit<AppointmentInfo, 'id' | 'createTime'>) => {
    const newAppointment: AppointmentInfo = {
      ...appointment,
      id: Date.now() + Math.random(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
    };

    
    appointments.value.unshift(newAppointment); // 添加到预约记录中
    return newAppointment;
  };

  const updateAppointmentStatus = (appointmentId: number, status: AppointmentInfo['status']) => {
    const appointment = appointments.value.find(apt => apt.id === appointmentId);
    if (appointment) {
      appointment.status = status;
    }
  };

  const cancelAppointment = (appointmentId: number) => {
    updateAppointmentStatus(appointmentId, '已取消');
  };

  // 慢病相关方法
  const addChronicDisease = (disease: Omit<ChronicDisease, 'id' | 'createTime'>) => {
    const newDisease: ChronicDisease = {
      ...disease,
      id: Date.now() + Math.random(),
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
    };
    chronicDiseases.value.unshift(newDisease);
    return newDisease;
  };

  const updateDiseaseStatus = (diseaseId: number, status: ChronicDisease['status']) => {
    const disease = chronicDiseases.value.find(d => d.id === diseaseId);
    if (disease) {
      disease.status = status;
    }
  };

  // 健康数据相关方法
  const addHealthMetric = (metric: Omit<HealthMetric, 'id'>) => {
    const newMetric: HealthMetric = {
      ...metric,
      id: Date.now() + Math.random()
    };
    healthMetrics.value.unshift(newMetric);
    
    // 只保留最近100条记录
    if (healthMetrics.value.length > 100) {
      healthMetrics.value = healthMetrics.value.slice(0, 100);
    }
    
    return newMetric;
  };

  const getHealthMetricsByType = (type: HealthMetric['type'], limit = 10) => {
    return healthMetrics.value
      .filter(metric => metric.type === type)
      .slice(0, limit)
      .sort((a, b) => new Date(b.recordTime).getTime() - new Date(a.recordTime).getTime());
  };

  // 处方相关方法
  const addPrescription = (prescription: Omit<Prescription, 'id'>) => {
    const newPrescription: Prescription = {
      ...prescription,
      id: Date.now() + Math.random()
    };
    prescriptions.value.unshift(newPrescription);
    return newPrescription;
  };

  const updatePrescriptionStatus = (prescriptionId: number, status: Prescription['status']) => {
    const prescription = prescriptions.value.find(p => p.id === prescriptionId);
    if (prescription) {
      prescription.status = status;
    }
  };

  // 新增：医院相关方法
  const setCurrentHospital = (hospital: HospitalInfo) => {
    currentHospital.value = hospital;
    console.log('设置当前医院:', hospital);
  };

  const getCurrentHospital = () => {
    return currentHospital.value;
  };

  const clearCurrentHospital = () => {
    currentHospital.value = null;
    console.log('清空当前医院');
  };

  // 清除数据方法
  const clearAppointments = () => {
    appointments.value = [];
  };

  const clearChronicDiseases = () => {
    chronicDiseases.value = [];
  };

  const clearHealthMetrics = () => {
    healthMetrics.value = [];
  };

  const clearPrescriptions = () => {
    prescriptions.value = [];
  };

  const clearAllData = () => {
    clearAppointments();
    clearChronicDiseases();
    clearHealthMetrics();
    clearPrescriptions();
  };

  return {
    // 状态
    appointments,
    currentMedicalCard,
    currentAppointment,
    chronicDiseases,
    healthMetrics,
    prescriptions,
    patientCards,
    currentHospital,
    
    // 计算属性
    upcomingAppointments,
    pendingPaymentAppointments,
    activeChronicDiseases,
    recentHealthMetrics,
    pendingPrescriptions,
    
    // 预约相关方法
    addAppointment,
    updateAppointmentStatus,
    cancelAppointment,
    
    // 慢病相关方法
    addChronicDisease,
    updateDiseaseStatus,
    
    // 健康数据相关方法
    addHealthMetric,
    getHealthMetricsByType,
    
    // 处方相关方法
    addPrescription,
    updatePrescriptionStatus,
    
    // 新增：就诊卡方法
    setCurrentMedicalCard,
    clearCurrentMedicalCard,
    getCurrentMedicalCard,
    setPatientCards,
    fetchPatientCards,
    setCurrentAppointment,
    getCurrentAppointment,
    clearCurrentAppointment,
    
    // 新增：医院方法
    setCurrentHospital,
    getCurrentHospital,
    clearCurrentHospital,
    
    // 清除数据方法
    clearAppointments,
    clearChronicDiseases,
    clearHealthMetrics,
    clearPrescriptions,
    clearAllData
  };
}, {
  persist: true
});